import 'package:aero_frisbee/gen/assets.gen.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_sound/flutter_sound.dart';
import 'package:rongcloud_im_wrapper_plugin/rongcloud_im_wrapper_plugin.dart';
import 'package:svgaplayer_flutter/svgaplayer_flutter.dart';

class AfMessageVoiceCell extends ConsumerStatefulWidget {
  const AfMessageVoiceCell({required this.message, super.key});

  final RCIMIWVoiceMessage message;
  @override
  ConsumerState<ConsumerStatefulWidget> createState() =>
      _AfMessageVoiceCellState();
}

class _AfMessageVoiceCellState extends ConsumerState<AfMessageVoiceCell>
    with SingleTickerProviderStateMixin {
  SVGAAnimationController? animationController;
  final FlutterSoundPlayer _soundPlayer = FlutterSoundPlayer();
  bool _playing = false;
  bool get isSelf {
    return widget.message.direction == RCIMIWMessageDirection.send;
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () {
        _stopVoiceMessage();
        _playVoiceMessage();
      },
      child: Padding(
        padding: isSelf
            ? const EdgeInsets.only(left: 6)
            : const EdgeInsets.only(right: 6),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            if (!isSelf)
              if (_playing)
                SizedBox(
                  height: 10,
                  child: SVGAImage(
                    animationController!,
                    fit: BoxFit.contain,
                    clearsAfterStop: false,
                    allowDrawingOverflow: true,
                    filterQuality: FilterQuality.low,
                  ),
                )
              else
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 10),
                  child: Assets.images.chat.chatVoiceRight.image(height: 10),
                ),
            Text(
              '${widget.message.duration}“',
              style: const TextStyle(
                color: Color(0xff202020),
                fontWeight: FontWeight.normal,
                fontSize: 16,
              ),
              textAlign: TextAlign.center,
              overflow: TextOverflow.ellipsis,
              maxLines: 1,
            ),
            if (isSelf)
              if (_playing)
                SizedBox(
                  height: 10,
                  child: SVGAImage(
                    animationController!,
                    fit: BoxFit.contain,
                    clearsAfterStop: false,
                    allowDrawingOverflow: true,
                    filterQuality: FilterQuality.low,
                  ),
                )
              else
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 19),
                  child: Assets.images.chat.chatVoiceLeft.image(height: 10),
                )
          ],
        ),
      ),
    );
  }

  _playVoiceMessage() {
    animationController?.repeat();

    _soundPlayer.openPlayer();
    setState(() {
      _playing = true;
    });
    _soundPlayer.startPlayer(
      fromURI: widget.message.remote ?? '',
      whenFinished: () {
        _stopVoiceMessage();
      },
    );
  }

  _stopVoiceMessage() {
    animationController?.stop();
    setState(() {
      _playing = false;
    });
    if (_soundPlayer.isPlaying) {
      _soundPlayer.stopPlayer();
    }
  }

  @override
  void initState() {
    animationController = SVGAAnimationController(vsync: this);
    _loadAnimation();
    super.initState();
  }

  void _loadAnimation() async {
    final videoItem = await SVGAParser.shared.decodeFromAssets(
        isSelf ? Assets.svga.videoRight : Assets.svga.videoLeft);

    if (mounted) {
      animationController?.videoItem = videoItem;
    }
  }

  @override
  void dispose() {
    animationController?.stop();
    animationController?.dispose();

    if (_soundPlayer.isPlaying) {
      _soundPlayer.stopPlayer();
    }

    super.dispose();
  }

  @override
  void didUpdateWidget(AfMessageVoiceCell oldWidget) {
    super.didUpdateWidget(oldWidget);
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
  }
}
